﻿using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using Classified.Data;
using Classified.Data.Repositories;
using Classified.Domain.Entities;
//using Webdiyer.WebControls.Mvc;
using System.Collections.Generic;
using Classified.Service;
using Classified.Web.Areas.Admin.Models;
using Classified.Web.Helpers;
using MvcPaging;


namespace Classified.Web.Areas.Admin.Controllers
{
    [CustomAuthorize(RequiredRole = "Admin")]
    public class AdminController : Controller
    {
        //
        // GET: /Admin/Admin/
        private readonly ILocationRepository _locationRepository;
        private readonly ICountryRepository _countryRepository;
        private readonly IOrderTypeRepositories _orderTypeRepositories;
        private readonly IClassifiedRepository _classifiedRepository;
        private readonly ICurrencyRepository _currencyRepository;
        private readonly IMyAccountRepositories _myAccountRepositories;
        private readonly IQueuedEmailRepositories _queuedEmailRepositories;


        private readonly string EmailFrom = ConfigurationManager.AppSettings["EmailFrom"];
        private readonly string AdminEmail = ConfigurationManager.AppSettings["AdminMail"];
        public AdminController(ILocationRepository locationRepository,
            ICountryRepository countryRepository,
                               IOrderTypeRepositories orderTypeRepositories,
            IClassifiedRepository classifiedRepository,
            ICurrencyRepository currencyRepository,
            IMyAccountRepositories myAccountRepositories,
            IQueuedEmailRepositories queuedEmailRepositories)
        {
            _locationRepository = locationRepository;
            _orderTypeRepositories = orderTypeRepositories;
            _classifiedRepository = classifiedRepository;
            _countryRepository = countryRepository;
            _currencyRepository = currencyRepository;
            _myAccountRepositories = myAccountRepositories;
            _queuedEmailRepositories = queuedEmailRepositories;
        }


        public ActionResult Index()
        {

            return View();
        }

        #region Location

        public ActionResult Locations(int countryId)
        {

            return View(countryId);
        }

        public List<SelectListItem> GetAllCountries(int selectedId)
        {
            var categories = _countryRepository.GetAll().OrderByDescending(x => x.DisplayOrder).ToList();

            var selectList = new List<SelectListItem>();
            foreach (var c in categories)
                selectList.Add(new SelectListItem()
                                   {
                                       Value = c.Id.ToString(),
                                       Text = c.Name,
                                       Selected = c.Id == selectedId
                                   });
            return selectList;

            //var selectList = new SelectList(categories, "Id", "Name", selectedId);
            // return new JsonResult { Data = selectList, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        /*CUSTOM*/
        public List<SelectListItem> GetStateByCountry(int selectedId, int countryId)
        {
            var location = _locationRepository.GetMany(x => x.CountryId == countryId && x.ParentId == 0).ToList();
            location.Insert(0, new Location { Name = "[None]", Id = 0 });
            var selectList = new List<SelectListItem>();
            foreach (var c in location)
                selectList.Add(new SelectListItem()
                {
                    Value = c.Id.ToString(),
                    Text = c.Name,
                    Selected = c.Id == selectedId
                });
            return selectList;


        }
        public List<Location> GetAllServiceCategoriesWithBreadCrumb(int countryId)
        {

            var data = _locationRepository.GetMany(x => x.CountryId == countryId).ToList();


            var categories = data.Select(item => new Location()
            {
                Id = item.Id,
                Name = item.GetLocationBreadCrumbMore(_locationRepository),
                IsActive = item.IsActive,
                IsDefault = item.IsDefault,
                UrlName = item.UrlName



            }).ToList();
            return categories;
        }
        public PartialViewResult LocationList(int countryId)
        {
            var countryname = _countryRepository.GetById(countryId);
            var data = GetAllServiceCategoriesWithBreadCrumb(countryId); //_locationRepository.GetMany(x => x.CountryId == countryId);
            ViewBag.CountryName = countryname.Name;
            return PartialView("_PartialLocationList", data);
        }

        public ActionResult CreateLocation(int countryId)
        {
            ViewBag.ParentId = GetStateByCountry(0, countryId);
            var model = new Location();
            model.CountryId = countryId;
            if (Request.IsAjaxRequest())
            {
                return PartialView(model);
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult CreateLocation(Location model)
        {

            if (ModelState.IsValid)
            {
                if (_locationRepository.IsLocationNameAvailabel(model.Name))
                {
                    var countryname = _countryRepository.GetById(model.CountryId);

                    model.UrlName = model.Name + "-" + countryname.TwoLetterIsoCode;
                    _locationRepository.Add(model);

                    var data = GetAllServiceCategoriesWithBreadCrumb(model.CountryId);
                    ViewBag.CountryName = countryname.Name;
                    return PartialView("_PartialLocationList", data);
                }
                else
                {
                    ModelState.AddModelError("Name", "location name already exists. Please enter a different Location name.");
                }
            }


            this.Response.StatusCode = 400;
            return PartialView(model);

        }

        public ActionResult EditLocation(int id)
        {

            var data = _locationRepository.GetById(id);
            ViewBag.ParentId = GetStateByCountry(data.ParentId, data.CountryId);
            if (Request.IsAjaxRequest())
            {

                return PartialView(data);
            }
            return View(data);
        }

        [HttpPost]
        public ActionResult EditLocation(Location model)
        {
            var _dataContext = new ClassifiedContext();
            if (ModelState.IsValid)
            {
                var curentlocation = _locationRepository.GetById(x => x.Id == model.Id);
                if (curentlocation.Name == model.Name || _locationRepository.IsLocationNameAvailabel(model.Name))
                {

                    var countryname = _countryRepository.GetById(model.CountryId);

                    model.UrlName = model.Name + "-" + countryname.TwoLetterIsoCode;

                    _dataContext.Entry(model).State = EntityState.Modified;
                    _dataContext.SaveChanges();
                    var data = GetAllServiceCategoriesWithBreadCrumb(model.CountryId);
                    ViewBag.CountryName = countryname.Name;
                    return PartialView("_PartialLocationList", data);
                }
            }
            else
            {
                ModelState.AddModelError("Name", "location name already exists. Please enter a different Location name.");
                ViewBag.ParentId = GetStateByCountry(0, model.CountryId);
                return PartialView(model);

            }
            this.Response.StatusCode = 400;
            return PartialView(model);
        }

        public ActionResult DeleteLocation(int id)
        {
            var data = _locationRepository.GetById(id);
            if (data != null)
                _locationRepository.Delete(data);
            return RedirectToAction("Locations", new { countryId = data.CountryId });

        }

        #endregion

        #region OrderType

        public ActionResult Settings()
        {
            return View();
        }

        public ActionResult ClassifiedList()
        {
            var data = _orderTypeRepositories.GetAll();
            return PartialView("_PartialClassifiedSettingList", data);
        }

        public ActionResult CreateClassifiedSetting()
        {
            var data = new OrderType();
            return PartialView(data);

        }

        [HttpPost]
        public ActionResult CreateClassifiedSetting(OrderType model)
        {
            if (ModelState.IsValid)
            {
                _orderTypeRepositories.Add(model);
                var data = _orderTypeRepositories.GetAll();
                return PartialView("_PartialClassifiedSettingList", data);
            }
            return PartialView(model);
        }

        public ActionResult EditClassifiedSetting(int id)
        {
            var data = _orderTypeRepositories.GetById(id);
            
            
            
            return PartialView(data);
        }

        [HttpPost]
        public ActionResult EditClassifiedSetting(OrderType model)
        {
            if (ModelState.IsValid)
            {
                _orderTypeRepositories.Update(model);
                var data = _orderTypeRepositories.GetAll();
                return PartialView("_PartialClassifiedSettingList", data);
            }
            return PartialView(model);
        }

        public ActionResult DeleteClassifiedsetting(int id)
        {
            _orderTypeRepositories.Delete(x => x.Id == id);
            return RedirectToAction("Settings");
        }

        #endregion

        public ActionResult FreeClassifiedList(int? page)
        {
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            // PagedList<ClassifiedAd> freelist;
            var freelist =
                _classifiedRepository.Filter(x => !x.IsEnhanced && !x.Deleted).OrderBy(x => x.Id).ToPagedList(
                    currentPageIndex, 5);
            return PartialView(freelist);
        }

        public ActionResult FeaturedClassifiedList(int? page)
        {
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            // var PagedList<ClassifiedAd> featurelist;
            var featurelist =
                _classifiedRepository.Filter(x => x.IsEnhanced).OrderBy(x => x.Id).ToPagedList(currentPageIndex, 5);
            if (Request.IsAjaxRequest())
            {
                return PartialView(featurelist);
            }
            return PartialView(featurelist);
        }
        public ActionResult CountryList(int? page)
        {
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            var data = _countryRepository.GetAll().OrderBy(x => x.Name).ToPagedList(currentPageIndex, 15);
            return PartialView(data);
        }
        public ActionResult Countries()
        {
            return View();
        }

        public ActionResult CreateCountry()
        {
            var data = new CountryCurrencyViewModel();
            if (Request.IsAjaxRequest())
            {

                return PartialView(data);
            }
            return View(data);
        }

        [HttpPost]
        public ActionResult CreateCountry(CountryCurrencyViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (_countryRepository.IsCountryNameAvailabel(model.Countries.Name))
                {
                    var country = new Country()
                                      {
                                          Name = model.Countries.Name,
                                          NumericIsoCode = model.Countries.NumericIsoCode,
                                          ThreeLetterIsoCode = model.Countries.ThreeLetterIsoCode,
                                          TwoLetterIsoCode = model.Countries.TwoLetterIsoCode,
                                          DisplayOrder = model.Countries.DisplayOrder
                                      };
                    _countryRepository.Add(country);

                    var current = new Currency()
                                      {
                                          Currency_Name = model.Currencies.Currency_Name,
                                          CountryId = country.Id,
                                          Currency_Sign = model.Currencies.Currency_Sign,
                                          ISO_Code = model.Currencies.ISO_Code

                                      };
                    _currencyRepository.Add(current);
                    int currentPageIndex = 1;
                    var data = _countryRepository.GetAll().OrderBy(x => x.Name).ToPagedList(currentPageIndex, 15);
                    return PartialView("Countries", data);
                }
                else
                {
                    ModelState.AddModelError("Name",
                                             "Country name already exists. Please enter a different Country name.");

                    return PartialView(model);
                }
            }
            return PartialView(model);


        }

        public ActionResult EditCountry(int id)
        {
            var country = _countryRepository.GetById(id);
            var currency = _currencyRepository.GetById(x => x.CountryId == country.Id);
            var viewmodel = new CountryCurrencyViewModel
                                {
                                    Countries = country,
                                    Currencies = currency
                                };
           
            if (Request.IsAjaxRequest())
            {

                return PartialView(viewmodel);
            }
            return View(viewmodel);
        }

        [HttpPost]
        public ActionResult EditCountry(CountryCurrencyViewModel model)
        {
            
                var country = _countryRepository.GetById(model.Countries.Id);
                if (country.Name == model.Countries.Name || _countryRepository.IsCountryNameAvailabel(model.Countries.Name))
                {
                    var _dataContext = new ClassifiedContext();
                    _dataContext.Entry(model.Countries).State = EntityState.Modified;
                    _dataContext.SaveChanges();
                    
                    if(model.Currencies.Id != 0)
                    {
                        var _dataContext1 = new ClassifiedContext();
                        _dataContext1.Entry(model.Currencies).State = EntityState.Modified;
                        _dataContext1.SaveChanges();
                       
                    }
                    else
                    {
                        var current = new Currency
                        {
                            Currency_Name = model.Currencies.Currency_Name,
                            CountryId = country.Id,
                            Currency_Sign = model.Currencies.Currency_Sign,
                            ISO_Code = model.Currencies.ISO_Code

                        };
                        _currencyRepository.Add(current);

                    }
                    int currentPageIndex = 1;
                    var data = _countryRepository.GetAll().OrderBy(x => x.Name).ToPagedList(currentPageIndex, 15);
                    return PartialView("Countries",data);
                }
                else
                {
                    ModelState.AddModelError("Name", "Country name already exists. Please enter a different Country name.");
                    return PartialView(model);

                }
           
        }

        public ActionResult DeleteCountry(int id)
        {
            var data = _countryRepository.GetById(id);
            _countryRepository.Delete(data);
            return RedirectToAction("Countries");
        }
        public ActionResult MyAccount(int? page)
        {
             int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            
            var data = _myAccountRepositories.GetAll().OrderByDescending(x=>x.SentDate).ToPagedList(currentPageIndex, 15);
            return View(data);
        }
        public ActionResult EmailDetail(int id)
        {
            var data = _myAccountRepositories.GetById(x => x.Id == id);
            return View(data);
        }
        public ActionResult ReplyToSender(int id)
        {
            var data = _myAccountRepositories.GetById(x => x.Id == id);
            var view = new QueuedEmail {To = data.Sender_EmailAddress, CreatedOnUtc = DateTime.UtcNow};
            return View(view);
        }
        [HttpPost]
        public ActionResult ReplyToSender(QueuedEmail model)
        {
            var objQueuedEmail = new QueuedEmail();
            bool emailSendStatus = false;
            emailSendStatus = EmailHelper.SendEmail(AdminEmail, model.To, model.Subject,
                                                    model.Body, EmailFrom);
            

            if (!emailSendStatus)
           {
                objQueuedEmail.IsSent = false;
                objQueuedEmail.SentOnUtc = DateTime.UtcNow;
            objQueuedEmail.To = model.To;
            objQueuedEmail.From = AdminEmail;
            objQueuedEmail.Body = model.Body;
            objQueuedEmail.CreatedOnUtc = DateTime.UtcNow;
            objQueuedEmail.FromName = EmailFrom;
            objQueuedEmail.SentTries = 0;
            objQueuedEmail.Subject = model.Subject;
_queuedEmailRepositories.Add(objQueuedEmail);

            }
            
            return RedirectToAction("MyAccount");

        }



    }
}
